<?php
namespace ApiBundle\Controller;

use AppBundle\Entity\EntUser;
use AppBundle\Service\lib\Aes;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * @abstract 用户管理相关的数据接口操作控制器类
 * @package ApiBundle\Controller
 */
class ApiUserNoLoginController extends ApiCommonController{


    /**
     * @abstract 存储客户端提交的用户注册
     * @Route("/app/user/save",name="app_user_save")
     */
    function saveUserInfo(Request $request){
        //返回信息数据
        $_strReturn = '';
        //验证header头所带的信息是否合法
        $_strCheckInfo = $this->checkHeaderInfo($request);
        $_objCheckInfo = json_decode($_strCheckInfo);
        if($_objCheckInfo->status == 0){//header头数据验证失败
            $_strReturn = $this->get('common_service')->apiEnCode($_objCheckInfo->status,$_objCheckInfo->message,[],400);
        }else if($_objCheckInfo->status == 1) {//header头数据验证成功
            $_arrParams = $request->request->all();
            if($_arrParams['phone'] != '' && !is_null($_arrParams['phone'])){//以电话号码直接注册的形式处理
                $em = $this->getDoctrine()->getManager();
                //根据手机号码进行查询,查询当前注册的手机号码是否已经注册过了
                $_objUser = $em->getRepository('AppBundle:EntUser')->findOneByTelephone($_arrParams['phone']);
                if($_objUser){//当前用户已经存在了
                    $_strReturn = $this->get('common_service')->apiEnCode('1','用户名已存在,请直接登录','',200);
                }else{
                    //创建客户端登录用户的角色
                    $_objAppUser = new EntUser();
                    $_objAppUser->setUsername('yixunfuns_'.$_arrParams['phone']);
                    $_objAppUser->setTelephone($_arrParams['phone']);
                    $_objAppUser->setPassword($_arrParams['password']);
                    $_objAppUser->setStatus(1);
                    $_objAppUser->setCreateTime(time());
                    //存储用户的token信息和对应的失效时间
                    $_objAppUser->setToken($this->get('common_service')->getAppLoginToken($_arrParams['phone']));
                    $_objAppUser->setTimeout(time('+7 days'));
                    $em->persist($_objAppUser);
                    $em->flush();
                    if($_objAppUser->getId()){//用户存储成功
                        $_arrReturn = array(
                            'userid'=> $_objAppUser->getId(),
                            'token'=> $_objAppUser->getToken()
                        );
                        //将返回的token和对应的用户id加密之后返回给客户端
                        $_strEncryptCode = $this->get('common_service')->encryptSign($_arrReturn);
                        $_strReturn = $this->get('common_service')->apiEnCode('1','注册成功',$_strEncryptCode,200);
                    }else{//存储失败
                        $_strReturn = $this->get('common_service')->apiEnCode('0','注册失败，请重试','',400);
                    }
                }
            }
        }
        return new Response($_strReturn);
    }


    /**
     * @abstract 客户端用户登录，如果用户是首次登录，也就是没有使用密码直接登录了，或者是免密登录界面那么还需要存储用户的注册信息
     * @param Request $request
     * @Route("/app/user/login",name="user_login")
     */
    function appUserLogin(Request $request)
    {
        $_strReturn = $this->get('common_service')->apiEnCode('0', '密码错误，登录失败',[], 200);
        return new Response($_strReturn);
        $_strReturn = '';
        //免密登录的情况下使用的是手机号码加短信验证码的方式登录
        $_arrPostData = $request->request->all();
        //判断电话号码是否存在
        if (is_null($_arrPostData['phone']) || $_arrPostData['phone'] == '') {
            $_strReturn = $this->get('common_service')->apiEnCode('0', '手机号码非法', '', 400);
            return new Response($_strReturn);
        }
        //判断验证码是否为空
        $_objAes = new Aes();
        if (array_key_exists('code', $_arrPostData)) {//验证码免密方式处理登录
            if (is_null($_arrPostData['code']) || $_arrPostData['code'] == '') {
                $_strReturn = $this->get('common_service')->apiEnCode('0', '短信验证码为空', '', 400);
                return new Response($_strReturn);
            }
            $_strCode =  $this->get('common_service')->getCodeSms($_arrPostData['phone']);//调用生成随机验证码
            if ($_strCode ==  $_objAes->cryptoJsAesDecrypt($request->get('code'))) {//验证码是加密传输的对比之前需要先解密
                //根据手机号码进行查询,查询当前注册的手机号码是否已经注册过了
                $em = $this->getDoctrine()->getManager();
                $_objUser = $em->getRepository('AppBundle:EntUser')->findOneByTelephone($request->get('phone'));
                if ($_objUser) {//当前用户已经存在了
                    //用户已经存在的情况下更新token和对应的过期时间
                    $_objUser->setToken($this->get('common_service')->getAppLoginToken($request->get('phone')));
                    $_objUser->setTimeout(time('+7 days'));
                    $em->flush();
                    $_arrReturn = array(
                        'userid' => $_objUser->getId(),
                        'token' => $_objUser->getToken()
                    );
                    //将返回的token和对应的用户id加密之后返回给客户端
                    $_strEncryptCode = $this->get('common_service')->encryptSign($_arrReturn);
                    $_strReturn = $this->get('common_service')->apiEnCode('1', '登录成功', $_strEncryptCode, 200);
                    return new Response($_strReturn);
                } else {
                    //创建客户端登录用户的角色
                    $_objAppUser = new EntUser();
                    $_objAppUser->setUsername('yixunfuns_' . $request->get('phone'));
                    $_objAppUser->setTelephone($request->get('phone'));
                    $_objAppUser->setStatus(1);
                    $_objAppUser->setCreateTime(time());
                    //存储用户的token信息和对应的失效时间
                    $_objAppUser->setToken($this->get('common_service')->getAppLoginToken($request->get('phone')));
                    $_objAppUser->setTimeout(time('+7 days'));
                    $em->persist($_objAppUser);
                    $em->flush();
                    if ($_objAppUser->getId()) {//用户存储成功
                        $_arrReturn = array(
                            'userid' => $_objAppUser->getId(),
                            'token' => $_objAppUser->getToken()
                        );
                        //将返回的token和对应的用户id加密之后返回给客户端
                        $_strEncryptCode = $this->get('common_service')->encryptSign($_arrReturn);
                        $_strReturn = $this->get('common_service')->apiEnCode('1', '登录成功', $_strEncryptCode, 200);
                        return new Response($_strReturn);
                    } else {//存储失败
                        $_strReturn = $this->get('common_service')->apiEnCode('0', '登录失败，请重试', '', 400);
                        return new Response($_strReturn);
                    }
                }
            } else {//输入验证码和实际发送验证码不一致
                $_strReturn = $this->get('common_service')->apiEnCode('0', '短信验证码错误', '', 400);
                return new Response($_strReturn);
            }
        } else if (array_key_exists('password', $_arrPostData)) {//账号密码方式实现登录
            if (is_null($_arrPostData['password']) || $_arrPostData['password'] == '') {
                $_strReturn = $this->get('common_service')->apiEnCode('0', '密码为空', '', 400);
                return new Response($_strReturn);
            }

            //根据手机号码进行查询,查询当前注册的手机号码是否已经注册过了
            $em = $this->getDoctrine()->getManager();
            $_objUser = $em->getRepository('AppBundle:EntUser')->findOneByTelephone($request->get('phone'));
            if ($_objUser) {//当前用户已经存在了
                //比对用户输入的密码是否正确
                $_strPassword = $_objAes->encrypt($_objAes->cryptoJsAesDecrypt($request->get('password')));//传输解密之后再使用后台加密
                if($_strPassword == $_objUser->getPassword()){
                    //用户已经存在的情况下更新token和对应的过期时间
                    $_objUser->setToken($this->get('common_service')->getAppLoginToken($request->get('phone')));
                    $_objUser->setTimeout(time('+7 days'));
                    $em->flush();
                    $_arrReturn = array(
                        'userid' => $_objUser->getId(),
                        'token' => $_objUser->getToken()
                    );
                    //将返回的token和对应的用户id加密之后返回给客户端
                    $_strEncryptCode = $this->get('common_service')->encryptSign($_arrReturn);
                    $_strReturn = $this->get('common_service')->apiEnCode('1', '登录成功', $_strEncryptCode, 200);
                    return new Response($_strReturn);
                }else{
                    $_strReturn = $this->get('common_service')->apiEnCode('0', '密码错误，登录失败',[], 200);
                    return new Response($_strReturn);
                }
            } else {//当前用户不存在提示需要注册
                $_strReturn = $this->get('common_service')->apiEnCode('0', '当前用户不存在', [], 200);
                return new Response($_strReturn);
            }
        }
    }

    /**
     * @abstract 测试路由
     * @Route("/adminuser/test",name="adminuser_test")
     */
    function test(Request $request){
//        $_str = 'AQHJOWBdSz+XY2tjM5nBU5TD8cbedVDmqFM6oowGI/A7opFy99pwBnvjoWZfFHyxVA8ngViWHpEV/I5UJJaTj6phx9BdP0E78WAL9aikV5f+DqKOCySQM5E8+RLbYA46hnSzF175oHfEp/+d4av5oaROU1Vic7A+03szrURTu2Y=';
        $_strToken = 'Aplj1rPeAMcSE0AkzRbAEx6yk8IkOm3Cq79ISiXhJsLD+ntl9eNM3esUA20QUtuTSJOklDE7P5F8O2Sz+WgDyQ==';
        $_arrReturn = array(
            'time'=> $this->get('common_service')->get13TimeStamp(),
            'token'=> $_strToken
        );
        $_strSign = $this->get('common_service')->encryptSign($_arrReturn);
        print_r($_strSign);exit;
//        $_str = 'F8bw22xWOBPlYeWTQt4j4F5wn/uqKrYUYVX0onziWSM7opFy99pwBnvjoWZfFHyxVA8ngViWHpEV/I5UJJaTj6phx9BdP0E78WAL9aikV5f+DqKOCySQM5E8+RLbYA46hnSzF175oHfEp/+d4av5oaROU1Vic7A+03szrURTu2Y=';
//        $_strSign = $this->get('common_service')->decryptSign($_str);
//        print_r(urldecode($_strSign));exit;
        //验证数据请求头
        $arrData = [
            'id' => '1',
            'did' =>'123123123',
            'time' => $this->get('common_service')->get13TimeStamp()
        ];
        //加密数据VjCFzLBaPLjoSWPYVho0BO0ZP7YBh3tENkvvzsRp+DRmnFEl0iHueoGCj0C0RDVFhkNVqtX8RHttsPpGJqXtiA==
        $_strSign = $this->get('common_service')->encryptSign($arrData);
        echo $_strSign;exit;
    }

    /**
     * @abstract 页面测试路由
     * @Route("/page/test",name="page_test")
     */
    function pageTest(Request $request){
          //加密测试页面（前端加密后端解密）
//          return $this->render('ApiBundle:Default:endecrypt.html.twig');
        //加密测试页面（后端加密前端解密）
        return $this->render('ApiBundle:Default:noendecrypt.html.twig');
//        return $this->render('ApiBundle:Default:index.html.twig');
    }

    /**
     * @abstract 加密解密测试路由
     * @Route("/endecrypt/test",name="endecrypt_test")
     */
    function endecryptTest(Request $request){
        //创建aes类对象
        $_objAes = new Aes();
        $_strDecrypt = $_objAes->cryptoJsAesDecrypt($_objAes->key,$request->get('encrypttext'));
        return new Response($_strDecrypt);
    }

}